package com.yyj.web.interceptor;

import com.yyj.constant.ReturnCode;
import com.yyj.constant.WebConstant;
import com.yyj.pojo.user.SessionInfo;
import com.yyj.util.RspUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Service
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();

        SessionInfo sessionInfo = (SessionInfo)request.getSession().getAttribute(WebConstant.SESSION_INFO);
        if(null == sessionInfo){
            response.setHeader("Content-Type", WebConstant.PRODUCES_TYPE_JSON);
            PrintWriter out = response.getWriter();
            out.print(RspUtils.needLoginStr());
            return false;
        }else if (requestURI.startsWith("/auth/manager")){
            if(!sessionInfo.isAdmin()){
                response.setHeader("Content-Type", WebConstant.PRODUCES_TYPE_JSON);
                PrintWriter out = response.getWriter();
                out.print(RspUtils.errorStr("非管理员用户"));
                return false;
            }
        }


        return true;

    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}